﻿using Microsoft.Extensions.Options;
using MimeKit;
using MailKit.Net.Smtp;


namespace TrackSystem.EmailService
{
    /// <summary>
    /// 邮件发送器类
    /// </summary>
    public class EmailSender : IEmailSender
    {
        private readonly FromEmailConfig fromEmail;

        public EmailSender(IOptions<FromEmailConfig> fromEmail)
        {
            this.fromEmail = fromEmail.Value;
        }

        public void SendEmail(Message message)
        {
            var emailMessage = CreateEmailMessage(message);
            Send(emailMessage);
        }

        public async Task SendEmailAsync(Message message)
        {
            var emailMessage = CreateEmailMessage(message);
            await SendAsync(emailMessage);
        }

        private MimeMessage CreateEmailMessage(Message message)
        {
            var emailMessage = new MimeMessage();
            emailMessage.From.Add(new MailboxAddress(fromEmail.Name, fromEmail.Address));
            emailMessage.To.Add(message.To);
            emailMessage.Subject = message.Subject;

            var bodyBuilder = new BodyBuilder
            {
                HtmlBody = $"<h2 style='color: red;'> {message.Content} </h2>"
            };
            emailMessage.Body = bodyBuilder.ToMessageBody();
            return emailMessage;
        }

        private void Send(MimeMessage mailMessage)
        {
            using var client = new SmtpClient();
            try
            {
                client.Connect(fromEmail.SmtpServer, fromEmail.Port, true);
                client.Authenticate(fromEmail.UserName, fromEmail.Password);
                client.Send(mailMessage);
            }
            finally
            {
                client.Disconnect(true);
                client.Dispose();
            }
        }

        private async Task SendAsync(MimeMessage mailMessage)
        {
            using var client = new SmtpClient();
            try
            {
                await client.ConnectAsync(fromEmail.SmtpServer, fromEmail.Port, true);
                await client.AuthenticateAsync(fromEmail.UserName, fromEmail.Password);
                await client.SendAsync(mailMessage);
            }
            finally
            {
                await client.DisconnectAsync(true);
                client.Dispose();
            }
        }
    }
}
